#include <stdlib.h>
#include <malloc.h>
#include <assert.h>
#include <string.h>
#include <tcDatabase/tc_chessboard.h>

typedef struct 
{
	int id;
	int value;
	tcType owner;
	tcType size;
	BOOL dead;
	BOOL enlarged;
	BOOL betrayed;
} tc_chessman;

typedef struct
{
	tc_chessman chessmen[32];
} tc_chessboard;

static tc_chessboard g_chessboard;

static tc_chessman* get_chessman_ptr(int id)
{
	return &g_chessboard.chessmen[id];
}

BOOL tc_database_init()
{
	memset(&g_chessboard, 0, sizeof(tc_chessboard));
	return true;
}

void tc_database_exit()
{

}

static int get_value_from_size(tcType size)
{
	int values[] = {8, 4, 2};
	return values[size];
}

int tc_chessman_create(const tc_chessman_init_desc *desc)
{
	tc_chessman *chessman = NULL;
	static int index = 0;

	assert(index < TC_CHESSMEN_MAX_NUMBER);

	chessman = &g_chessboard.chessmen[index];
	chessman->id = index;
	chessman->owner = desc->init_owner;
	chessman->size = desc->init_size;
	chessman->value = get_value_from_size(desc->init_size);

	return index++;
}

void tc_chessman_reset( int id )
{
	tc_chessman *chessman = get_chessman_ptr(id);
	chessman->dead = false;
	if (chessman->enlarged)
	{
		chessman->enlarged = false;
		chessman->size++;
		chessman->value = get_value_from_size(chessman->size);
	}
	if (chessman->betrayed)
	{
		chessman->betrayed = false;
		chessman->owner = !chessman->owner;
	}
}


tcType tc_chessman_get_owner(int id)
{
	return get_chessman_ptr(id)->owner;
}

tcType tc_chessman_get_size( int id )
{
	return get_chessman_ptr(id)->size;
}

int tc_chessman_get_value( int id )
{
	return get_chessman_ptr(id)->value;
}

void tc_chessman_set_dead( int id, BOOL dead )
{
	get_chessman_ptr(id)->dead = dead;
}

BOOL tc_chessman_get_dead( int id )
{
	return get_chessman_ptr(id)->dead;
}

void tc_chessman_change( int id )
{
	tc_chessman* ptr = get_chessman_ptr(id);
	ptr->betrayed = !ptr->betrayed;
	ptr->owner = !ptr->owner;
	
}

BOOL tc_chessman_enlarge( int id )
{
	tc_chessman* ptr = get_chessman_ptr(id);
	if (ptr->enlarged == true || ptr->size == TC_CHESSMAN_SIZE_LARGE)
	{
		return false;
	}
	ptr->enlarged = true;
	ptr->size--;
	ptr->value = get_value_from_size(ptr->size);
	return true;
}

